import { defineComponent, defineAsyncComponent, h, computed, watch, ref } from 'vue'
import type { PropType } from 'vue'
import type { questionSideListState } from '@/types/baseConfig'
import { NSpin } from 'naive-ui'

export default defineComponent({
  name: 'DynamicComponent',
  props: {
    compData: {
      type: Object as PropType<questionSideListState>,
      default: () => {
        return {}
      }
    },
    component: {
      type: String,
      required: true
    }
  },
  emits: ['save'],
  setup(props, { emit }) {
    const pageLoading = ref<boolean>(true)
    const handSave = (e: questionSideListState) => {
      emit('save', e)
    }
    const modules = import.meta.glob(['./*.tsx'])
    const AsyncComponent = computed(() => {
      const link: any = modules[`./${props.component}.tsx`]
      if (link) {
        return defineAsyncComponent(link)
      }
      return null
    })
    let oldUid = ''
    watch(
      () => props.compData,
      (newVal: questionSideListState) => {
        if (newVal.uid === oldUid) return
        oldUid = newVal.uid
        pageLoading.value = true
        setTimeout(() => {
          pageLoading.value = false
        }, 400)
      },
      {
        immediate: true
      }
    )
    // markRaw
    return () => (
      <>
        {pageLoading.value ? (
          <div class="flex justify-center pt-[30px]">
            <NSpin size="small" />
          </div>
        ) : (
          AsyncComponent.value &&
          h(AsyncComponent.value, {
            'comp-data': props.compData,
            onSave: handSave
          })
        )}
      </>
    )
  }
})
